package org.dromara.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import org.dromara.admin.domain.Order;
import org.dromara.admin.domain.OrderProductPrice;
import org.dromara.admin.domain.bo.OrderBo;
import org.dromara.admin.domain.bo.OrderProductPriceBo;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.domain.vo.ProductVo;
import org.dromara.admin.domain.vo.SystemConfigVo;
import org.dromara.admin.enums.GeneralEnum;
import org.dromara.admin.service.*;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.OrderProductBo;
import org.dromara.admin.domain.vo.OrderProductVo;
import org.dromara.admin.domain.OrderProduct;
import org.dromara.admin.mapper.OrderProductMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 订单产品明细关联Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OrderProductServiceImpl implements IOrderProductService {

    private final OrderProductMapper baseMapper;
    private final IProductService productService;
    private final IOrderProductPriceService orderProductPriceService;
    private final ISystemConfigService systemConfigService;

    /**
     * 查询订单产品明细关联
     *
     * @param id 主键
     * @return 订单产品明细关联
     */
    @Override
    public OrderProductVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询订单产品明细关联列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 订单产品明细关联分页列表
     */
    @Override
    public TableDataInfo<OrderProductVo> queryPageList(OrderProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OrderProduct> lqw = buildQueryWrapper(bo);
        Page<OrderProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的订单产品明细关联列表
     *
     * @param bo 查询条件
     * @return 订单产品明细关联列表
     */
    @Override
    public List<OrderProductVo> queryList(OrderProductBo bo) {
        LambdaQueryWrapper<OrderProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OrderProduct> buildQueryWrapper(OrderProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OrderProduct> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(OrderProduct::getId);
        lqw.eq(bo.getOrderId() != null, OrderProduct::getOrderId, bo.getOrderId());
        lqw.eq(bo.getProductId() != null, OrderProduct::getProductId, bo.getProductId());
        lqw.eq(bo.getQuantity() != null, OrderProduct::getQuantity, bo.getQuantity());
        lqw.eq(bo.getUnitPrice() != null, OrderProduct::getUnitPrice, bo.getUnitPrice());
        lqw.like(StringUtils.isNotBlank(bo.getProductName()), OrderProduct::getProductName, bo.getProductName());
        lqw.eq(StringUtils.isNotBlank(bo.getProductImg()), OrderProduct::getProductImg, bo.getProductImg());
        lqw.eq(StringUtils.isNotBlank(bo.getProductSpecs()), OrderProduct::getProductSpecs, bo.getProductSpecs());
        lqw.eq(StringUtils.isNotBlank(bo.getProductUnit()), OrderProduct::getProductUnit, bo.getProductUnit());
        return lqw;
    }

    /**
     * 新增订单产品明细关联
     *
     * @param bo 订单产品明细关联
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OrderProductBo bo) {
        OrderProduct add = MapstructUtils.convert(bo, OrderProduct.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改订单产品明细关联
     *
     * @param bo 订单产品明细关联
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OrderProductBo bo) {
        OrderProduct update = MapstructUtils.convert(bo, OrderProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OrderProduct entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除订单产品明细关联信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 创建订单时保存订单产品明细
     *
     * @param bo 订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrderPAnd2PByOrderBo(OrderBo bo) {
        // === 查询系统配置，判断一客一价开关 ===
        SystemConfigVo systemConfigVo = systemConfigService.queryConfigInfoByEmployeeId(bo.getCreatorId());
        boolean customerPriceMode = systemConfigVo != null && GeneralEnum.Y.equals(systemConfigVo.getCustomerPrice());

        List<OrderProductBo> orderProductList = bo.getOrderProductList(); // 订单中产品明细
        if (CollUtil.isNotEmpty(orderProductList)) {
            List<OrderProduct> itemList = new ArrayList<>();
            for (OrderProductBo itemBo : orderProductList) {
                // 查询产品信息
                ProductVo product = productService.queryById(itemBo.getProductId());
                // 判断产品是否属于当前公司
                if (!bo.getCompanyId().equals(product.getCompanyId())) {
                    throw new ServiceException("产品：" + product.getName() + "不属于当前主体公司！");
                }

                OrderProduct item = new OrderProduct();
                item.setOrderId(bo.getId());
                item.setProductId(product.getId());
                item.setQuantity(itemBo.getQuantity());
                item.setUnitPrice(itemBo.getUnitPrice());
                item.setProductName(product.getName());
                item.setProductImg(product.getProductImg());
                item.setProductSpecs(product.getSpec());
                item.setProductUnit(product.getUnit());
                itemList.add(item);

                // === 同步订单产品价格记录表 ===
                // 先判断该产品+客户是否存在记录
                OrderProductPrice orderProductPrice =
                    orderProductPriceService.queryByProductIdAndCustomerIdAndOrderType(product.getId(), bo.getCustomerId(), bo.getOrderType());
                BigDecimal finalPrice;
                if (customerPriceMode) {
                    // 一客一价开启 → 使用前端传入的价格
                    finalPrice = itemBo.getUnitPrice();
                } else {
                    // 未开启 → 使用产品表价格
                    finalPrice = product.getUnitPrice();
                }

                if (BeanUtil.isEmpty(orderProductPrice)) {
                    // 新增记录
                    orderProductPrice = new OrderProductPrice();
                    orderProductPrice.setEmployeeId(bo.getCreatorId());
                    orderProductPrice.setProductId(product.getId());
                    orderProductPrice.setCustomerId(bo.getCustomerId());
                    orderProductPrice.setCustomerType(bo.getCustomerType());
                    orderProductPrice.setProductPrice(finalPrice);
                    orderProductPrice.setOrderType(bo.getOrderType());
                    orderProductPrice.setOrderCount(1);
                    orderProductPrice.setOrderProductCount(itemBo.getQuantity());
                    orderProductPrice.setTotalAmount(itemBo.getUnitPrice().multiply(new BigDecimal(itemBo.getQuantity())));
                    orderProductPriceService.insertByBo(BeanUtil.copyProperties(orderProductPrice, OrderProductPriceBo.class));
                } else {
                    // 更新记录（增加开单次数和产品数量）
                    orderProductPrice.setEmployeeId(bo.getCreatorId());
                    orderProductPrice.setOrderCount(orderProductPrice.getOrderCount() + 1);
                    orderProductPrice.setOrderProductCount(orderProductPrice.getOrderProductCount() + itemBo.getQuantity());
                    orderProductPrice.setProductPrice(finalPrice);
                    orderProductPrice.setTotalAmount(orderProductPrice.getTotalAmount().add(itemBo.getUnitPrice().multiply(new BigDecimal(itemBo.getQuantity()))));
                    orderProductPriceService.updateByBo(BeanUtil.copyProperties(orderProductPrice, OrderProductPriceBo.class));
                }
            }
            // 批量插入明细
            baseMapper.insertBatch(itemList);
        }
    }
}
